package logic

import (
	"context"
	"time"
	"xialou_platform/app/cryptx"
	"xialou_platform/app/errorx"
	"xialou_platform/app/jwtx"
	"xialou_platform/services/system/rpc/systemClient"

	"xialou_platform/services/system/api/internal/svc"
	"xialou_platform/services/system/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) LoginLogic {
	return LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	sysUser, err := l.svcCtx.SystemRpc.SysUserByName(l.ctx, &systemClient.SysUserByNameReq{Name: req.Account})
	if err != nil {
		return nil, err
	}

	if sysUser.Password != cryptx.PasswordEncrypt(sysUser.Salt, req.Password) {
		return nil, errorx.NewDefaultError("用户密码错误。")
	}

	now := time.Now().Unix()

	accessExpire := l.svcCtx.Config.Auth.AccessExpire

	accessToken, err := jwtx.GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, sysUser.Id, 0)

	if err != nil {
		return nil, err
	}

	resp = &types.LoginResp{
		AccessToken:  accessToken,
		AccessExpire: accessExpire,
		Role:         sysUser.Role,
	}
	return resp, nil
}
